<script>
import { useDeviceStore, useGlobalStore } from '@/stores/'
export default {
  onLaunch: function () {
    // console.log('App Launch')
    // 蓝牙订阅事件名称
    uni.$myNotifyEventName = 'notify'
    // CRC-16/MODBUS 校验
    function crc16modbus(data) {
      const dataBytes = data.map((v) => parseInt(v, 16))
      let crc = 0xffff
      const polynomial = 0xa001 // This is the polynomial x^16 + x^15 + x^2 + 1

      for (const byte of dataBytes) {
        crc ^= byte
        for (let i = 0; i < 8; i++) {
          if (crc & 0x0001) {
            crc = ((crc >> 1) ^ polynomial) & 0xffff
          } else {
            crc >>= 1
          }
        }
      }
      return crc.toString(16).toUpperCase().padStart(4, '0').match(/\w{2}/g).reverse()
    }
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      })
      // console.log('ab2hex: ', hexArr)
      return hexArr
    }
    //监听设备发送数据
    uni.onBLECharacteristicValueChange((res) => {
      // console.log('listenNotify Change：', res)
      const deviceStore = useDeviceStore()
      const optsNotify = deviceStore.getOpts().notify
      if (!optsNotify) return
      if (
        optsNotify.deviceId === res.deviceId &&
        optsNotify.serviceId === res.serviceId &&
        optsNotify.characteristicId === res.characteristicId
      ) {
        // buffer转16进制字符串数组
        const resData = ab2hex(res.value)
        // 校验数据
        // console.log('listenNotify resData', resData)
        const crc = crc16modbus(resData.slice(0, -2)).join('').toUpperCase()
        const crcRes = resData.slice(-2).join('').toUpperCase()
        if (crcRes !== crc) {
          throw new Error('crc校验失败，数据错误')
        }
        uni.$emit(uni.$myNotifyEventName, resData)
      }
    })
    // 监听蓝牙连接变化
    uni.onBLEConnectionStateChange(function (res) {
      const globalStore = useGlobalStore()
      if (res.connected) {
        globalStore.addConnDeviceList(res.deviceId)
      } else {
        globalStore.removeConnDeviceList(res.deviceId)
      }
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
    })
  },
  onShow: function () {
    // 屏幕常亮
    // #ifndef WEB
    uni.setKeepScreenOn({
      keepScreenOn: true,
      // success: (success) => {
      //   console.log('屏幕常亮')
      // },
    })
    // #endif
  },
  onHide: function () {
    // console.log('App Hide')
  },
  // 捕获 app error
  onError(err) {
    console.log('捕获error:', err)
    // uni.$globalMessage.alert({
    //   msg: '捕获error:' + err,
    //   title: '提示',
    // })
    uni.hideLoading()
  },
  // https://ask.dcloud.net.cn/article/35021
  globalData: {
    text: 'text',
    protosUtils: {},
  },
}
</script>

<style lang="scss">
/*每个页面公共css */
@import '@/common/styles/common-style.scss';
@import '@/common/styles/base-style.scss';
@import '@/common/styles/icon.scss';
</style>
